<?php
/*
 * @Description    : 
 * @Author         : QianLong
 * @Date           : 2023-03-22 16:07:13
 * @LastEditors    : QianLong
 * @Site           : http://www.21ds.cn
 * @LastEditTime   : 2023-03-23 10:26:12
 */

declare(strict_types=1);

namespace app\driver\log;

use DateTime;
use DateTimeZone;
use think\App;
use think\contract\LogHandlerInterface;
use think\facade\Request;

/**
 * 本地化调试输出到文件
 */
class Log implements LogHandlerInterface
{
    /**
     * 配置参数
     * @var array
     */
    protected $config = [
        'time_format' => 'c',
        'apart_level' => true,
        'json' => false,
        'json_options' => JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES,
    ];

    protected $app;

    // 实例化并传入参数
    public function __construct(App $app, $config = [])
    {
        $this->app = $app;

        if (is_array($config)) {
            $this->config = array_merge($this->config, $config);
        }
    }

    /**
     * 日志写入接口
     * @access public
     * @param array $log 日志信息
     * @return bool
     */
    public function save(array $log): bool
    {
        // 日志信息封装
        $time = DateTime::createFromFormat('0.u00 U', microtime())->setTimezone(new DateTimeZone(date_default_timezone_get()))->format($this->config['time_format']);

        $request = Request::instance();
        $requestInfo = [];
        //新增
        $requestInfo = [
            'log_time' => $time,
            'ip' => $request->ip(),
            'method' => $request->method(),
            'uri' => $request->url(true)
        ];

        $requestInfo['param'] = json_encode($request->param());
        $runtime = round(microtime(true) - $this->app->getBeginTime(), 10);
        $reqs = $runtime > 0 ? number_format(1 / $runtime, 2) : '∞';
        $memory_use = number_format((memory_get_usage() - $this->app->getBeginMem()) / 1024, 2);
        $requestInfo['run_time'] = number_format($runtime, 6) . 's [吞吐率：' . $reqs . 'req/s]';
        $requestInfo['memory_use'] = $memory_use . 'kb';
        $requestInfo['file_load'] = count(get_included_files());

        $apartData = '';
        foreach ($log as $type => $val) {
            foreach ($val as $msg) {
                if (!is_string($msg)) {
                    $msg = var_export($msg, true);
                }
                if (true === $this->config['apart_level'] || in_array($type, $this->config['apart_level'])) {
                    $apartData .= "\r\n".sprintf($this->config['format'], $time, $type, $msg);
                }
            }
        }
        $requestInfo['apart'] = $apartData;
        $requestInfo['log'] = json_encode($log);
        return $this->write($requestInfo);
    }

    protected function write(array $data): bool
    {

        // $postData['content'] = json_encode($data);
        $http = new \Yurun\Util\HttpRequest;
        // file_put_contents(PUBLIC_PATH.'/../runtime/log.txt',json_encode($data));
        sysLogPush($data, $http, true);
        return true;
    }
}
